package guoanmaker.operator.business.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.service.OperatorUserServiceInterface;

@Component
public class OperatorUserValidator implements Validator{
	
	@Autowired
    private OperatorUserServiceInterface provideUserServiceInterface;
	
	@Override
    public boolean supports(Class<?> aClass) {
        return OperatorUser.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
    	OperatorUser user = (OperatorUser) o;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty");
        if (user.getUsername().length() < 6 || user.getUsername().length() > 32) {
            errors.rejectValue("username", "Size.userForm.username");
        }
        if (provideUserServiceInterface.getByUsername(user.getUsername()) != null) {
            errors.rejectValue("username", "Duplicate.userForm.username");
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
        if (user.getPassword().length() < 8 || user.getPassword().length() > 32) {
            errors.rejectValue("password", "Size.userForm.password");
        }

    }

}
